package com.hyjx.framework.common;

import com.hyjx.framework.common.util.SpringBeanUtil;
import com.hyjx.framework.common.util.StringHelper;
import com.hyjx.framework.service.CacheService;
import com.hyjx.framework.uc.depart.DepartService;
import com.hyjx.framework.uc.user.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户信息监听对象
 *
 * @author dijian
 */
public class OnlineUserListener implements HttpSessionBindingListener {
    private UserInfo user;
    Logger log = LoggerFactory.getLogger(OnlineUserListener.class);
    private DepartService service;
    
    /**
     * 构造方法
     *
     * @param user
     */
    public OnlineUserListener(UserInfo user) {
        user.setLogin_time(StringHelper.getDateTime());
        service = (DepartService) SpringBeanUtil.getBean(Constants.DEPART_SERVICE_NAME);
        if (user.isSuperAdmin())
            user.setDepart_code_fullcn("-");
        else {
            if (user.getDepart() != null) {
                user.setDepart_code_fullcn(service.getFullDepartCN(user.getDepart().getDepart_code()));
            }
        }
        this.user = user;
    }
    
    /**
     * 用户登陆后，绑定用户信息
     */
    public void valueBound(HttpSessionBindingEvent event) {
        List<UserInfo> onlineUserList = (List<UserInfo>) CacheService.get("onlineUserList");
        if (onlineUserList == null) {
            onlineUserList = new ArrayList<UserInfo>();
            CacheService.set("onlineUserList", onlineUserList);
        }
        onlineUserList.add(this.user);
        log.debug(this.user.getUser_name() + "login");
    }
    
    /**
     * 用户注销时，删除用户信息
     */
    public void valueUnbound(HttpSessionBindingEvent event) {
        List<UserInfo> onlineUserList = (List<UserInfo>) CacheService.get("onlineUserList");
        onlineUserList.remove(this.user);
        log.debug(this.user.getUser_name() + "logout");
    }
}
